<?php
/**
 * @author Jumper Swordwave
 * date: 2021/04/19
 */
declare(strict_types=1);
namespace App\Game\Core;

/**
 * game request
 */
class Request
{
    /**
     * @var integer
     * websocket link
     */
    private $fd;

    /**
     * @var integer
     * command type
     */
    private $command;

    /**
     * @var integer
     * status code
     */
    private $code;

    /**
     * @var string
     * error message
     */
    private $message;

    /**
     * @var array
     * user info
     */
    private $user;

    /**
     * @var array
     * request data
     */
    private $data;

    public function __construct(int $fd, int $code, int $command, string $message, ?array $data = [], ?array $user = [])
    {
        $this->fd = $fd;
        $this->code = $code;
        $this->command = $command;
        $this->message = $message;
        $this->data = $data;
        $this->user = empty($user) ? null : $user;
    }

    public static function newRequest(int $fd, int $code, int $command, string $message, ?array $data = [], ?array $user = [])
    {
        return new static($fd, $code, $command, $message, $data, $user);
    }

    /**
     * 解析数据生成请求
     */
    public static function parser(int $fd, array $data)
    {
        return new static($fd, intval($data['code']), intval($data['command']), $data['message'] ?? '', $data['data'] ?? [], $data['user'] ?? null);
    }

    public function getFd()
    {
        return $this->fd;
    }

    public function getCommand()
    {
        return $this->command;
    }
    
    public function getCode()
    {
        return $this->code;
    }
    
    public function getMessage()
    {
        return $this->message;
    }
    
    public function getData()
    {
        return $this->data;
    }

    public function getUser()
    {
        return $this->user;
    }

    public function input($field, $default = '')
    {
        return isset($this->data[$field]) ? $this->data[$field] : $default;
    }

    public function toArray()
    {
        return [
            'fd' => $this->fd,
            'code' => $this->code,
            'command' => $this->command,
            'message' => $this->message,
            'user' => $this->user,
            'data' => $this->data,
        ];
    }
}